package springboot.demo.modules.sys.controller;

import com.baidu.ueditor.ActionEnter;
import springboot.demo.common.exception.RRException;
import springboot.demo.modules.oss.cloud.OSSFactory;
import springboot.demo.modules.oss.entity.SysOssEntity;
import springboot.demo.modules.oss.service.SysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Date;

@RestController
public class UeditorController {
    @Autowired
    private SysOssService sysOssService;

    @RequestMapping("/ueditor/exec")
    public String ueditorConfig(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        String rootPath = request.getRealPath("/");
        String action = request.getParameter("action");
        if (action.equals("catchimage")) {
            return "";
        }
        return new ActionEnter(request, rootPath, UeditorController.class.getClassLoader()
                .getResource("ueditor.config.json").getPath()).exec();

    }

    @RequestMapping("/ueditor/ossUpload")
    public void ossUpload(@RequestParam("upfile") MultipartFile file, HttpServletResponse response) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build().uploadSuffix(file.getBytes(), suffix);

        //保存文件信息
        SysOssEntity ossEntity = new SysOssEntity();
        ossEntity.setUrl(url);
        ossEntity.setCreateDate(new Date());
        sysOssService.save(ossEntity);

        String result = "{\"title\":\"" + file.getOriginalFilename() + "\", \"original\": \"" + file.getOriginalFilename() + "\", \"state\": \"" + "SUCCESS" + "\", \"url\": \"" + url + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        response.getWriter().print(result);
    }
}
